<template>
  <div class="batch-create-loc">
    <el-form inline label-width="100px" label-position="right" ref="createForm" :model="inputData" :rules="rules">
      <template v-for="field in inputConfig">
        <el-form-item :label="$t(field.label)" :prop="field.props" >
          <template v-if="field.type == 'input'">
            <el-input v-model="inputData[field.props]" :placeholder="$t('common.input')" :disabled="field.disabled">
              <template v-if="field.unit" slot="append">{{field.unit}}</template>
            </el-input>
          </template>
          <template v-if="field.type == 'select'">
            <el-select v-model="inputData[field.props]" :placeholder="$t('common.select')" :disabled="field.disabled" filterable clearable @change="handleSelect($event,field)">
              <template>
                <el-option v-for="opt in options[field.api]" :key="opt.code" :label="opt.description" :value="opt.code"></el-option>
              </template>
            </el-select>
          </template>
          <template v-if="field.type == 'switch'">
            <el-switch v-model="inputData[field.props]" active-value="1" inactive-value="0" :disabled="field.disabled"> </el-switch>
          </template>
          <template v-if="field.type == 'inputSection'">
            <GInputSection :separator="field.separator" :sectionType="field.sectionType" :value="inputData[field.props]" @input="handleInputSection($event,field)"></GInputSection>
          </template>
        </el-form-item>
        <br v-if="field.break" />
        <hr v-if="field.line" />
      </template>
    </el-form>

    <template v-if="row_number>=0&&column_number>=0&&tier_number>=0">
      <div class="loc-list-wrap" :style="{height:height + 'px'}">
        <div class="loc-list-cell" v-for="cell in locList" :key="cell.loc">{{cell.loc}}</div>
      </div>
      <div class="batch-create-footer">
        <el-button type="primary" :disabled="!this.btnPermNameList.includes('WM030508')" @click="handleSubmit">{{$t("common.save")}}</el-button>
        <el-button :disabled="!this.btnPermNameList.includes('WM030509')">{{$t("common.cancel")}}</el-button>
      </div>
    </template>

  </div>
</template>

<script>
import { batchInputConfig, optionsInit } from '../data'
import baseMixin from '@/mixins/BaseMixin'

export default {
  name: 'batchCreate',
  mixins: [baseMixin],
  data() {
    return {
      inputConfig: batchInputConfig,
      inputData: { putawayzonename: '' },
      options: optionsInit(),
      countList: [],
      locList: [],
      rules: {
        // whsename:[ { required: true, message: '仓库名称不能为空' } ],
        // whseid:[ { required: true, message: '仓库编号不能为空' } ],
        // areakey:[ { required: true, message: '区域编号不能为空' } ],
        putawayzonename: [
          {
            required: true,
            message: this.$inputEmptyMes('config.putZoneName'),
            trigger: 'change'
          }
        ],
        // putawayzone:[ { required: true, message: '库区编号不能为空' } ],
        row_count: [
          {
            required: true,
            message: this.$inputEmptyMes('config.rowLength'),
            trigger: 'change'
          }
        ],
        row_number: [{ required: true }],
        column_number: [{ required: true }],
        tier_number: [{ required: true }],
        column_count: [
          {
            required: true,
            message: this.$inputEmptyMes('config.columnLength'),
            trigger: 'change'
          }
        ],
        tier_count: [
          {
            required: true,
            message: this.$inputEmptyMes('config.layerLength'),
            trigger: 'change'
          }
        ],
        codeRule: [
          {
            required: true,
            message: this.$inputEmptyMes('config.createCodeRule'),
            trigger: 'change'
          }
        ],
        locationtype: [
          {
            required: true,
            message: this.$inputEmptyMes('config.locType'),
            trigger: 'change'
          }
        ],
        locationflag: [
          {
            required: true,
            message: this.$inputEmptyMes('config.locFlag'),
            trigger: 'change'
          }
        ],
        locationcategory: [
          {
            required: true,
            message: this.$inputEmptyMes('config.locCategory'),
            trigger: 'change'
          }
        ],
        locationhandling: [
          {
            required: true,
            message: this.$inputEmptyMes('config.locHandler'),
            trigger: 'change'
          }
        ],
        abc: [
          {
            required: true,
            message: this.$inputEmptyMes('config.turnoverType'),
            trigger: 'change'
          }
        ]
        // quality_type:[ { required: true, message: '品质类型不能为空', trigger: 'change' } ],
        // control_property:[ { required: true, message: '控制属性不能为空', trigger: 'change' } ],
        // length:[ { required: true, message: '库位长度不能为空', trigger: 'blur' } ],
        // width:[ { required: true, message: '库位宽度不能为空', trigger: 'blur' } ],
        // height:[ { required: true, message: '库位高度不能为空', trigger: 'blur' } ],
        // max_load_count:[ { required: true, message: '最大承载数量不能为空', trigger: 'blur' } ],
        // weightcapacity:[ { required: true, message: '最大承载重量不能为空', trigger: 'blur' } ],
        // cubiccapacity:[ { required: true, message: '最大承载体积不能为空', trigger: 'blur' } ],
        // max_pack_count:[ { required: true, message: '最大容器数量不能为空', trigger: 'blur' } ],
      },
      height: 300
    }
  },
  computed: {
    row_number() {
      let num = -1,
        number = this.inputData.row_number
      if (number && number.length == 2 && number[1] >= number[0]) {
        num = number[1] - number[0] + 1
      }
      return num
    },
    column_number() {
      let num = -1,
        number = this.inputData.column_number
      if (number && number.length == 2 && number[1] >= number[0]) {
        num = number[1] - number[0] + 1
      }
      return num
    },
    tier_number() {
      let num = -1,
        number = this.inputData.tier_number
      if (number && number.length == 2 && number[1] >= number[0]) {
        num = number[1] - number[0] + 1
      }
      return num
    },
    prepend() {
      let str = ''
      const { whseid, areakey, putawayzone } = this.inputData
      if (whseid && areakey && putawayzone) {
        if (this.inputData.codeRule == '12201') {
          str = areakey + '-' + putawayzone + '-'
        } else if (this.inputData.codeRule == '12202') {
          str = putawayzone + '-'
        } else if (this.inputData.codeRule == '12204') {
          str = putawayzone + '-'
        } else if (this.inputData.codeRule == '12203') {
          str = ''
        }
      }
      return str
    }
  },
  watch: {
    inputData: {
      handler(nv) {
        if (
          this.row_number >= 0 &&
          this.column_number >= 0 &&
          this.tier_number >= 0
        ) {
          this.createInit()
        }
      },
      deep: true
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          const inputData = this.inputData
          if (!inputData.whseid) {
            return this.$message.error(this.$inputEmptyMes('config.wareCode'))
          }
          let params = []
          for (let r = 0; r < this.row_number; r++) {
            for (let c = 0; c < this.column_number; c++) {
              for (let t = 0; t < this.tier_number; t++) {
                let putawayzone = this.prepend
                putawayzone += this.getLabelByIndex(r, 'row_count')
                putawayzone += '-'
                putawayzone += this.getLabelByIndex(c, 'column_count')
                if (this.inputData.codeRule == '12204') {
                  putawayzone += '-'
                }
                putawayzone += this.getLabelByIndex(t, 'tier_count')
                let obj = { loc: putawayzone, ...inputData }
                obj.row_number = inputData.row_number[0] + r
                obj.column_no = inputData.column_number[0] + c
                obj.layer_no = inputData.tier_number[0] + t
                params.push(obj)
              }
            }
          }
          console.table(params)
          if (params.length == 0) {
            return this.$message.error(this.$t('msg.msg4'))
          }
          this.$api.post('/rtxLocList/saveLocByList', params).then(res => {
            
              this.$message.success(
                this.$tj('config.batchCreate', 'config.loc', 'app.addMes')
              )
              this.$router.go(-1)
            
          })
        }
      })
    },
    createInit() {
      if (
        this.row_number >= 0 &&
        this.column_number >= 0 &&
        this.tier_number >= 0
      ) {
        let arr = []
        for (let r = 0; r < this.row_number; r++) {
          for (let c = 0; c < this.column_number; c++) {
            for (let t = 0; t < this.tier_number; t++) {
              let putawayzone = this.prepend
              putawayzone += this.getLabelByIndex(r, 'row_count')
              putawayzone += '-'
              putawayzone += this.getLabelByIndex(c, 'column_count')
              if (this.inputData.codeRule == '12204') {
                putawayzone += '-'
              }
              putawayzone += this.getLabelByIndex(t, 'tier_count')
              let obj = { loc: putawayzone, ...this.inputData }
              obj.row_number = this.inputData.row_number[0] + r
              arr.push(obj)
            }
          }
        }
        this.locList = arr
      }
    },
    getLabelByIndex(index, props, type) {
      const labelList = this.options.NumberDigit.map(item => item.code)
      let count = labelList.indexOf(this.inputData[props]) + 1
      let label = ''
      // if(props == "row_count"&&this.inputData.row_fix.length == 2){
      // count = count - this.inputData.row_fix[0].length-this.inputData.row_fix[1].length
      // count = count < index.toString().length ? index.toString().length : count;
      // label = this.inputData.row_fix[0] + Array(count - index.toString().length).fill("0").join('') + index + this.inputData.row_fix[1]
      // }
      let minStr =
        props == 'row_count'
          ? this.inputData.row_number[0]
          : props == 'column_count'
          ? this.inputData.column_number[0]
          : props == 'tier_count'
          ? this.inputData.tier_number[0]
          : 0
      minStr = type == 'split' ? index : parseInt(minStr) + index
      if (type == 'split') {
        console.log(index, props, minStr)
      }
      if (minStr.toString().length < count) {
        label =
          Array(count - minStr.toString().length)
            .fill('0')
            .join('') + minStr
        if (props == 'row_count' && this.inputData.row_fix.length == 2) {
          label =
            this.inputData.row_fix[0] +
            Array(count - index.toString().length)
              .fill('0')
              .join('') +
            minStr +
            this.inputData.row_fix[1]
        }
      } else {
        label = minStr.toString()
      }
      return label
    },
    handleSelect($event, field) {
      if (field.props == 'putawayzonename') {
        this.getInfoByName()
      } else if (field.props == 'codeRule') {
        this.createInit()
      }
    },
    handleInputSection($event, field) {
      this.inputData[field.props] = $event
    },
    getOptions() {
      const inputConfig = this.inputConfig
      let apiStrArr = []
      inputConfig.forEach(item => {
        if (item.type == 'inputSection') {
          this.$set(this.inputData, item.props, item.defaultValue || [])
        } else {
          this.$set(this.inputData, item.props, item.defaultValue || '')
        }
        if (item.api) {
          if (item.api.includes('/')) {
            this.$api.get(item.api).then(res => {
              this.options[item.api] = res.data
            })
          } else {
            apiStrArr.push(item.api)
          }
        }
      })
      this.$api
        .post('/rtxLocList/querycodeLkupByList', [...new Set(apiStrArr)])
        .then(res => {
          
            const data = res.data.list
            data.forEach(item => {
              this.options[item.codelkupName] = item.codelkupList
            })
          
        })
      // console.log(this.inputData,'this.inputData');
    },
    getInfoByName() {
      const putawayzonename = this.inputData.putawayzonename
      this.$api
        .get(`/rtxLocList/queryPutawayzoneByName/${putawayzonename}`)
        .then(res => {
          
            if (res.data.list.length > 0) {
              const data = res.data.list[0]
              Object.keys(this.inputData).forEach(key => {
                if (data[key]) {
                  this.inputData[key] = data[key]
                }
              })
            } else {
              this.$message.info(this.$inputEmptyMes('config.wareCode'))
            }
          
        })
    }
  },
  mounted() {
    this.height = this.getHeight(window, 500)
    this.getOptions()
  }
}
</script>
<style lang="scss" scoped>
.batch-create-loc {
  .el-form-item {
    vertical-align: middle;
    margin: 8px 10px;
    margin-left: 0;
    ::v-deep .el-form-item__content {
      vertical-align: middle;
    }
    .el-input,
    .el-select {
      width: 180px;
    }
  }
  .loc-list-wrap {
    overflow: auto;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    align-content: flex-start;
    .loc-list-cell {
      width: 10%;
      min-width: 120px;
      padding: 0.8em;
      text-align: center;
      margin: 0.5em;
      border: 1px solid #ddd;
      margin: 0.5em;
    }
  }
  .batch-create-footer {
    margin-top: 10px;
    padding: 10px 0;
    background: #f1f2f3;
    text-align: center;
  }
}
</style>